/*
 * Copyright (C) 2012 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * FClolorScaleEditor.java
 *
 * Created on Feb 29, 2012, 12:36:25 PM
 */
package ru.apertum.diasled.forms;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.WindowConstants;
import org.jdesktop.application.Action;
import ru.apertum.diasled.cfg.ColorScale;
import ru.apertum.diasled.cfg.Configuration;

/**
 * Диалог редактирования цветовой шкалы.
 * Задаётся максимум и минимум шкалы. Задается последовательность цветов для цветовой шкалы. 
 * Эти цвета равномерно распологаются в 16 сегментов и промежутки заполняются градиентом
 * @author Evgeniy Egorov
 */
public class FColorScaleEditor extends javax.swing.JDialog {

    /** Creates new form FClolorScaleEditor */
    private FColorScaleEditor(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        // свернем по esc
        getRootPane().registerKeyboardAction(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        },
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        try {
            setIconImage(ImageIO.read(DiasledView.class.getResource("/ru/apertum/diasled/forms/resources/favicon.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }

        buttonClearActionPerformed(null);
        listColors.setCellRenderer(new ListCellRenderer() {

            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                final JLabel l = new JLabel("" + (ColorScale.DIVISIONS - index));
                l.setOpaque(true);
                l.setBackground((Color) value);
                return l;
            }
        });
    }
    private Configuration cfg;

    public void load(Configuration cfg) {
        this.cfg = cfg;
        final Color[] cs = new Color[ColorScale.DIVISIONS];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = i < cfg.getColorScale().getColors().size() ? new Color(cfg.getColorScale().getColors().get(i), false) : Color.WHITE;
        }
        listColors.setModel(new DefaultComboBoxModel(cs));
    }

    private void save() {
        cfg.getColorScale().getColors().clear();
        for (int i = 0; i < listColors.getModel().getSize(); i++) {
            cfg.getColorScale().getColors().add(((Color) listColors.getModel().getElementAt(i)).getRGB());
        }
    }

    public static FColorScaleEditor getInstance(Configuration cfg) {
        FClolorScaleEditorHolder.INSTANCE.setLocationRelativeTo(null);
        if (cfg != null) {
            FClolorScaleEditorHolder.INSTANCE.load(cfg);
        }
        return FClolorScaleEditorHolder.INSTANCE;
    }

    private static class FClolorScaleEditorHolder {

        private static final FColorScaleEditor INSTANCE = new FColorScaleEditor(null, true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSpinner1 = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jSpinner2 = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listColors = new javax.swing.JList();
        buttonClear = new javax.swing.JButton();
        buttonRGB = new javax.swing.JButton();
        buttonAutoPeint = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        buttonOK = new javax.swing.JButton();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getActionMap(FColorScaleEditor.class, this);
        jMenuItem3.setAction(actionMap.get("editColor")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        jPopupMenu1.add(jMenuItem3);

        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getResourceMap(FColorScaleEditor.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(2000, 100, 5000, 50));
        jSpinner1.setName("jSpinner1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jSpinner2.setModel(new javax.swing.SpinnerNumberModel(0, 0, 2000, 50));
        jSpinner2.setName("jSpinner2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane1.border.title"))); // NOI18N
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        listColors.setBackground(resourceMap.getColor("listColors.background")); // NOI18N
        listColors.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listColors.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listColors.setComponentPopupMenu(jPopupMenu1);
        listColors.setDragEnabled(true);
        listColors.setName("listColors"); // NOI18N
        listColors.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listColorsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listColors);

        buttonClear.setText(resourceMap.getString("buttonClear.text")); // NOI18N
        buttonClear.setName("buttonClear"); // NOI18N
        buttonClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonClearActionPerformed(evt);
            }
        });

        buttonRGB.setText(resourceMap.getString("buttonRGB.text")); // NOI18N
        buttonRGB.setName("buttonRGB"); // NOI18N
        buttonRGB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRGBActionPerformed(evt);
            }
        });

        buttonAutoPeint.setText(resourceMap.getString("buttonAutoPeint.text")); // NOI18N
        buttonAutoPeint.setName("buttonAutoPeint"); // NOI18N
        buttonAutoPeint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAutoPeintActionPerformed(evt);
            }
        });

        jPanel2.setName("jPanel2"); // NOI18N

        buttonOK.setText(resourceMap.getString("buttonOK.text")); // NOI18N
        buttonOK.setName("buttonOK"); // NOI18N
        buttonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(352, Short.MAX_VALUE)
                .addComponent(buttonOK)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonOK)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jSpinner2)
                            .addComponent(jSpinner1, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(buttonClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(buttonRGB, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(buttonAutoPeint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonClear)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonRGB)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonAutoPeint))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        save();
        setVisible(false);
    }

    @Action
    public void addColor() {
        final Color cc;
        if ((cc = JColorChooser.showDialog(rootPane, "Добавление цвета", Color.yellow)) != null) {
            final Color[] cs = new Color[listColors.getModel().getSize() + 1];
            cs[cs.length - 1] = cc;
            for (int i = 0; i < listColors.getModel().getSize(); i++) {
                cs[i] = (Color) listColors.getModel().getElementAt(i);
            }
            listColors.setModel(new DefaultComboBoxModel(cs));
        }
    }//GEN-LAST:event_buttonOKActionPerformed

    private void listColorsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listColorsMouseClicked
        if (evt.getClickCount() > 1) {
            editColor();
        }
    }//GEN-LAST:event_listColorsMouseClicked

    private void buttonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonClearActionPerformed
        final Color[] cc = new Color[ColorScale.DIVISIONS];
        for (int i = 0; i < cc.length; i++) {
            cc[i] = Color.WHITE;
        }
        listColors.setModel(new DefaultComboBoxModel(cc));
    }//GEN-LAST:event_buttonClearActionPerformed

    private void buttonRGBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRGBActionPerformed
        final Color[] cc = new Color[ColorScale.DIVISIONS];
        int k = ColorScale.DIVISIONS / 5;
        int max = 16;
        for (int value = 1; value <= ColorScale.DIVISIONS; value++) {

            int rowIndex = (max - value) / (max / ColorScale.DIVISIONS);
            //System.out.println("" + max + " " + value + " " + rowIndex);
            int g = (int) Math.round(255 - Math.abs(255 / (ColorScale.DIVISIONS - 2.5 * k) * (-ColorScale.DIVISIONS / 2 + rowIndex)));
            g = g < 0 ? 0 : g;
            //g = 0;

            int r = 255 - rowIndex * (255 / (ColorScale.DIVISIONS - k));
            r = r < 0 ? 0 : r;
            //r = 0;

            int b = (rowIndex - k) * (255 / (ColorScale.DIVISIONS - k));
            b = b < 0 ? 0 : b;
            //b = 0;

            cc[ColorScale.DIVISIONS - value] = new Color(r, g, b);
        }
        listColors.setModel(new DefaultComboBoxModel(cc));
    }//GEN-LAST:event_buttonRGBActionPerformed

    private void buttonAutoPeintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAutoPeintActionPerformed
        final Color[] cc = new Color[ColorScale.DIVISIONS];
        for (int i = 0; i < listColors.getModel().getSize(); i++) {
            cc[i] = ((Color) listColors.getModel().getElementAt(i));
        }
        Color first = null;
        Color last = null;
        Color pred = null;
        int s = 0;
        int i = 0;
        for (Color color : cc) {
            if (Color.WHITE.equals(color) && first == null) {
                first = pred == null ? Color.WHITE : pred;
                s = i;
            }
            if (!Color.WHITE.equals(color) && Color.WHITE.equals(pred)) {
                last = color;

                // ну и закрасим
                for (int j = s; j < i; j++) {
                    cc[j] = new Color(first.getRed() + (last.getRed() - first.getRed()) / (i - s + 1) * (j - s + 1),
                            first.getGreen() + (last.getGreen() - first.getGreen()) / (i - s + 1) * (j - s + 1),
                            first.getBlue() + (last.getBlue() - first.getBlue()) / (i - s + 1) * (j - s + 1));
                }
                first = null;
                last = null;
            }

            pred = color;
            i++;
        }
        if (first != null && Color.WHITE.equals(pred)) {
            last = Color.WHITE;
            // ну и закрасим
            for (int j = s; j < ColorScale.DIVISIONS; j++) {
                cc[j] = new Color(first.getRed() + (last.getRed() - first.getRed()) / (i - s + 1) * (j - s + 1),
                        first.getGreen() + (last.getGreen() - first.getGreen()) / (i - s + 1) * (j - s + 1),
                        first.getBlue() + (last.getBlue() - first.getBlue()) / (i - s + 1) * (j - s + 1));
            }
        }
        listColors.setModel(new DefaultComboBoxModel(cc));
    }//GEN-LAST:event_buttonAutoPeintActionPerformed

    @Action
    public void removeColor() {
        if (listColors.getSelectedIndex() != -1) {
            final Color[] cs = new Color[listColors.getModel().getSize() - 1];
            for (int i = 0; i < cs.length; i++) {
                cs[i] = (Color) listColors.getModel().getElementAt(i < listColors.getSelectedIndex() ? i : i + 1);
            }
            listColors.setModel(new DefaultComboBoxModel(cs));
        }
    }

    @Action
    public void editColor() {
        final Color cc;
        if (listColors.getSelectedIndex() != -1
                && (cc = JColorChooser.showDialog(rootPane, "Добавление цвета", (Color) listColors.getModel().getElementAt(listColors.getSelectedIndex()))) != null) {
            final Color[] cs = new Color[listColors.getModel().getSize()];
            for (int i = 0; i < listColors.getModel().getSize(); i++) {
                cs[i] = (Color) listColors.getModel().getElementAt(i);
            }
            cs[listColors.getSelectedIndex()] = cc;
            listColors.setModel(new DefaultComboBoxModel(cs));
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAutoPeint;
    private javax.swing.JButton buttonClear;
    private javax.swing.JButton buttonOK;
    private javax.swing.JButton buttonRGB;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JSpinner jSpinner2;
    private javax.swing.JList listColors;
    // End of variables declaration//GEN-END:variables
}
